#include <IP.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <IPException.h>

#include <iostream>

// Constructores
IP::IP()
{
}

IP::IP(string ip)
{
   struct in_addr ipaddr;
   struct hostent *he=NULL;
   
   memset(&ipaddr, 0, sizeof(struct in_addr));
   
   if (inet_aton(ip.c_str(), &ipaddr))
   {
      this->ip=ipaddr.s_addr;
      
      // resolucio inversa
      he=gethostbyaddr((char*)&this->ip, sizeof(dword), AF_INET);
      
      if (he!=NULL)
      {
	 string *strtmp=new string(he->h_name);
	 if (strtmp!=NULL)
	 {
	    name=*strtmp;
	    delete strtmp;
	 }
	 else
	    name=ip;
      }
      else
	 name=ip;
      return;
   }
   
   he=gethostbyname(ip.c_str());
   
   if (he!=NULL)
   {
      this->ip=*((dword*)(he->h_addr_list[0]));
      this->name=ip;
   }
   else
      throw IPException(string("Invalid IP Address"));
}

IP::IP(dword ip)
{
   struct in_addr ipaddr;
   struct hostent *he=NULL;
   
   memset(&ipaddr, 0, sizeof(struct in_addr));
   
   this->ip=ip;
   
   // resolucio inversa
   he=gethostbyaddr((char*)&this->ip, sizeof(dword), AF_INET);
   
   if (he!=NULL)
   {
      string *strtmp=new string(he->h_name);
      if (strtmp!=NULL)
      {
	 name=*strtmp;
	 delete strtmp;
      }
      else
	 name=toString();
   }
   else
      name=toString();
}

IP::~IP()
{
   
}

// Metodes
string IP::getHostname()
{
   return name;
}


dword IP::toDWord()
{
   return ip;
}


string IP::toString()
{
   string sip;
   
   for (int i=0; i<4; i++)
   {
      char aux[4];
      sprintf(aux, "%d", *(((byte*)(&this->ip))+i));
      sip.append(aux);
      if (i!=3) 
	 sip.append(".");
   }

   return (sip);
}
